
package com.mexcad.utils;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;

import com.mexcad.db.connectors.CreditoConnector;
import com.mexcad.db.connectors.SolicitudConnector;
import com.mexcad.db.dto.BeanCargaPago;
import com.mexcad.db.dto.CKCargoPago;
import com.mexcad.db.dto.CKCredito;
import com.mexcad.db.dto.CargoPago;
import com.mexcad.db.dto.Credito;
import com.mexcad.db.dto.Renta;
import com.mexcad.db.dto.RentaUploadMonto;
import com.mexcad.exceptions.ArchivoCargaException;

/**
 * This program reads a text file line by line and print to the console. It uses
 * FileOutputStream to read the file.
 * 
 */
public class LeeArchivo {

	
  public LeeArchivo(){}
  
  public static List<Credito> getListaCreditosCargados(DataInputStream dis) throws ArchivoCargaException,IOException,NumberFormatException{
	  List<Credito> listado = new ArrayList<Credito>();
      
	    try {
	       int ind=0;
	        // dis.available() returns 0 if the file does not have more lines.
	        while (dis.available() != 0) {

	      	 StringTokenizer st = new StringTokenizer(dis.readLine(),"&");
	      	 int i=0;
	      	 
	      	// while (st.hasMoreTokens()) {
	      		 Credito c = new Credito();
	      		 CKCredito fk  = new CKCredito();
	      		 fk.setIdCliente(new Integer(st.nextToken()).intValue());
	      		 c.setIdEjecutivo(new Integer(st.nextToken()).intValue());
	      		 st.nextToken(); // algo
	      		 fk.setIdCredito(new Integer(st.nextToken()).intValue());
	      		 st.nextToken(); //Descpiption
	      		 
	      		 c.setNombres(st.nextToken());
	      		 c.setApellidoPaterno(st.nextToken());
	      		 c.setApellidoMaterno(st.nextToken());
	      		// c.setDescripcion(c.getDescripcion()+" Num. N�mina: "+st.nextToken());
	      	//	 c.setDescripcion(c.getDescripcion()+" "+st.nextToken());
	       		 fk.setIdEsquemaCredito(new Integer(st.nextToken()));
	       		 c.setNumEmpleado(st.nextToken());
	       		 st.nextToken(); //desc
	       		 st.nextToken(); //desc
	       		 
	      		 c.setMontoCredito(new Double(st.nextToken()).doubleValue());
	      		 c.setIdMoneda(new Integer(st.nextToken()));
	      		 String val =st.nextToken();
	      		 
	      		 c.setFechaInicial(Formatter.getDateFromString(val));
	      		 c.setMontoPorPeriodo(new Double(st.nextToken()).doubleValue());
	      		  val =st.nextToken();
	      		 c.setPlazoSolicitado(new Integer(val.trim()).intValue());
	      		 c.setIdPeriodoSolicitado(new Integer( st.nextToken()));
	      		
	      		 c.setTasaBase(new Double(st.nextToken()).doubleValue());
	      		 st.nextToken();  // gracia de capital
	      		 c.setCalle(st.nextToken());
	      		 c.setNumExt(st.nextToken());
	      		 c.setNumInt(st.nextToken());
	      		 c.setColonia(st.nextToken());
	      		 c.setEstado(st.nextToken());
		      	 c.setPobDelegacion(st.nextToken());
	      		 c.setCp(st.nextToken());
	      		 st.nextToken();  //Estado
	      		 st.nextToken(); // email
	      		 val =st.nextToken();
	      		 fk.setIdTipoSolicitud(new Integer(val).intValue());
	      		 val =st.nextToken();
	      		 c.setIdTipoContrato(new Integer(val).intValue());
	      		 fk.setIdComisionista(new Integer(val).intValue());
	      		 
	      		 c.setCkCredito(fk);
	      		 
	      		 c.setIdEstatus(CreditoConnector.CREDITO_ACTIVO);
	      		 int meses=0;
	      		
	      	 
		      		 if(c.getIdPeriodoSolicitado() == SolicitudConnector.SEMANAL){
		      				meses=(int) Math.ceil((double)c.getPlazoSolicitado()/4);
		      			}else if(c.getIdPeriodoSolicitado() == SolicitudConnector.QUINCENAL ){
		      				meses= (int)Math.ceil((double)c.getPlazoSolicitado()/2);
		      				
		      			} else if(c.getIdPeriodoSolicitado() == SolicitudConnector.MENSUAL){
		      				meses= c.getPlazoSolicitado();
		      			} else if(c.getPlazoSolicitado() == SolicitudConnector.BIMESTRAL){
		      				meses=c.getPlazoSolicitado()*2;
		      			}
		      		 if(c.getCkCredito().getIdEsquemaCredito() != SolicitudConnector.ESQUEMA_UNAM && c.getCkCredito().getIdEsquemaCredito() != SolicitudConnector.ESQUEMA_UNAM_IVA){
			      		 if(meses <=10){
			      			 double cuota = SolicitudConnector.cuotaAdministracionPorMes[meses];
			      			 c.setCuota(cuota);
			      		 }else{
			      			 c.setCuota(0);
			      		 }
		      		 }
	      		 
	      		 
	      		// c.setCuota(0);
	      		 listado.add(c);
	      		 
	              // System.out.print("["+(i++)+" ]["++"], \t\t");
	           //}

	           System.out.println(c.getCkCredito().getIdCredito()+", "+ind++);
	      	 
	        // this statement reads the line from the file and print it to
	          // the console.
	          //System.out.println();
	        }
	        System.out.println(listado.size());
	        // dispose all the resources after using them.

	      } catch (IOException e) {
	       // e.printStackTrace();
	        throw e;
	      } catch (NumberFormatException e) {
	    	 // e.printStackTrace();
	    	  throw e;
		       // e.printStackTrace();
		       // System.out.println("Error.......");
		        
		  }
	      
	      
	  
	      return listado;
  }
	
  public static BeanCargaPago guardaPagosByStream(DataInputStream dis) throws ArchivoCargaException,IOException,NumberFormatException, Exception{
	  	List<RentaUploadMonto> listadoPagos = new ArrayList<RentaUploadMonto>();
	  	List<RentaUploadMonto> listadoPagosErroneos = new ArrayList<RentaUploadMonto>();
	  	double sumaMontos=0;
	  	try {
	       
	        // dis.available() returns 0 if the file does not have more lines.
	        while (dis.available() != 0) {
		         String linea = dis.readLine();
		         
		         StringTokenizer st = new StringTokenizer(linea," \t");
		         String []datos = new String[st.countTokens()];
			     int i=0;
			     while (st.hasMoreTokens()) {
			     	datos[i] = st.nextToken();
			     	i++;
			     }
		         String montoQuincenaStr = datos[1].substring(0,datos[1].indexOf("ZZ"));
		         String numCreditoStr =datos[datos.length-2];
		         String fechaPagoRenta = datos[datos.length-1];
		       //  System.out.println("Cred: "+new Integer(numCreditoStr)+", monto: "+((double)new Double(new Integer(montoQuincenaStr)/100)));
		         Integer numCredito =new Integer(numCreditoStr);
		         Double montoPago = new Double(new Double(montoQuincenaStr)/100);
		      
		         RentaUploadMonto ru = new RentaUploadMonto();
		         ru.setFecha(fechaPagoRenta);
		         ru.setIdCredito(numCredito.intValue());
		         ru.setMonto(montoPago.doubleValue());
		         listadoPagos.add(ru);
		         
	        }   
		         
		         
		         for(int j=0;j<listadoPagos.size();++j){
		        	 RentaUploadMonto r = listadoPagos.get(j);
		        	 Credito cred = CreditoConnector.getCreditoPorId(r.getIdCredito());
		        	 if(cred != null){
		        		 if(CreditoConnector.tieneRentasActivas(r.getIdCredito())){
		        			 int i=0;
		        			 Renta renta=null;
		        			 List<Renta> rentas = CreditoConnector.getAllRentasByCredito(r.getIdCredito());
		        			 for(i=0;i<rentas.size();++i){
		        				 renta = rentas.get(i);
		        				 if(renta.getIdEstatus() == CreditoConnector.RENTA_ACTIVA){
		        					 break;
		        				 }
		        			 }
		        			 
		        			 if(renta != null && renta.getIdEstatus()== CreditoConnector.RENTA_ACTIVA){
		        				 int id=0;
		        				id= CreditoConnector.ejecutaPagoRenta(renta.getCkRenta().getIdRenta(), r.getMonto(), r.getFecha());
		        				if(id!= 0 ){
			        				sumaMontos+=r.getMonto();
		        				}else{
		        					listadoPagosErroneos.add(r);
		        				}

		        			}else{
		        				listadoPagosErroneos.add(r);
		        			}
		        		}else{
	        				listadoPagosErroneos.add(r);
	        			}
		        		 
		        		 
		        	 }else{
	        				listadoPagosErroneos.add(r);
	        		 }
			     }
		    
	      
	      } catch (IOException e) {
	        e.printStackTrace();
	        throw e;
	      } catch (NumberFormatException e) {
	    	  throw e;
		       // e.printStackTrace();
		       // System.out.println("Error.......");
		        
		  }catch (Exception e) {
	    	  throw e;
		       // e.printStackTrace();
		       // System.out.println("Error.......");
		        
		  }
	      
		  BeanCargaPago bean = new BeanCargaPago();
		  bean.setMontoPago(sumaMontos);
		  bean.setLista(listadoPagosErroneos);
	      return bean;
  }
  
	
	
  public static void main(String[] args) {

    File file = new File("C:\\proyectos\\eas0909.pro");
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;


    
    try {
    	fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        dis = new DataInputStream(bis);

   
    	
        List<RentaUploadMonto> listado= new ArrayList();//  = guardaPagosByStream(dis);
   	 for(int i=0;i<listado.size();++i){
   		RentaUploadMonto c = listado.get(i);
   		 
   	 }

     // dis.available() returns 0 if the file does not have more lines.
     
     System.out.println(listado.size());
     // dispose all the resources after using them.
     fis.close();
     bis.close();
     dis.close();

   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (NumberFormatException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
    
    
  }
}

